package redis

import (
	"github.com/gomodule/redigo/redis"
	"strconv"
)

type RedisCache struct {
	Key string
	Value interface{}
	Exprie int
	Start int
	End int
}

func (self *RedisCache) SetCache() bool {
	conn := RedisClient.Get()
	defer conn.Close()
	var err error
	if self.Exprie <= 0 {
		_,err = conn.Do("SET", self.Key, self.Value)
	} else {
		_,err = conn.Do("SET", self.Key, self.Value, "EX", strconv.Itoa(self.Exprie))
	}

	if err != nil {
		return false
	}
	return true
}

func (self *RedisCache) GetCache() string  {
	conn := RedisClient.Get()
	defer conn.Close()
	value,err := redis.String(conn.Do("GET", self.Key))
	if err != nil {
		return ""
	}
	return value
}

func (self *RedisCache) Exists() bool  {
	conn := RedisClient.Get()
	defer conn.Close()
	ex,err := redis.Bool(conn.Do("EXISTS", self.Key))
	if err != nil {
		return false
	}
	return ex
}

func (self *RedisCache) Delete() bool {
	conn := RedisClient.Get()
	defer conn.Close()
	_,err := conn.Do("DEL", self.Key)
	if err != nil {
		return false
	}
	return true
}

func (self *RedisCache) Expire() int64  {
	conn := RedisClient.Get()
	defer conn.Close()
	num,err := redis.Int64(conn.Do("EXPIRE", self.Key, self.Exprie))
	if err != nil {
		return -1
	}
	return num
}

func (self *RedisCache) LPush() bool {
	conn := RedisClient.Get()
	defer conn.Close()
	_,err := conn.Do("lpush", self.Key, self.Value)
	if err != nil {
		return false
	}
	return true;
}

func (self *RedisCache) LRange() ([]string,error)  {
	conn := RedisClient.Get()
	defer conn.Close()
	values,err := redis.Values(conn.Do("lrange", self.Key, self.Start, self.End))
	if err != nil {
		return nil,err
	}
	var vals []string
	for _,v := range values{
		vals = append(vals, string(v.([]byte)))
	}
	return vals,nil
}
